﻿/**
 * GoText Palm: A program that allows to send text messages over the internet.
 *  Copyright (C) 2008 Nicola 'Gawaine' Racco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Reflection;
using GoTextPalm.Core;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Localization;
using GoTextPalm.Core.Persistence;

namespace GoTextPalm.Gui
{
    /// <summary>
    /// 
    /// </summary>
    /// <
    public partial class MainForm : LocalizedForm
    {
        private Logic logic;

        public MainForm()
        {
            logic = new Logic();
            logic.ErrorCausedEvent += new Logic.ErrorCausedHandler(Logic_ErrorCaused);
            logic.LoadProcedureClosedEvent += new Logic.LoadProcedureClosedHandler(Logic_LoadProcedureClosed);
            logic.StatusTextChangedEvent += new Logic.StatusTextChangedHandler(Logic_StatusTextChanged);

            InitializeComponent();
            new SplashForm().ShowDialog();
            AddColumnsToDictionary();
            AddMenusToDictionary();
            UpdateResources();
        }

        protected override void AddMenusToDictionary()
        {
            AddMenuToDictionary(mnuServices, "mnuServices");
            AddMenuToDictionary(mnuSetup, "mnuSetup");
            AddMenuToDictionary(mnuOther, "mnuOther");
            AddMenuToDictionary(mnuExit, "mnuExit");
            AddMenuToDictionary(mnuSaved, "mnuSaved");
            AddMenuToDictionary(mnuNew, "mnuNew");
            AddMenuToDictionary(mnuLastSent, "mnuLastSent");
        }

        protected override void AddColumnsToDictionary()
        {
            AddColumnToDictionary(clSrv, "clSrv");
            AddColumnToDictionary(clMex, "clMex");
        }

        private void mnuServices_Click(object sender, EventArgs e)
        {
            if (new ServicesForm().ShowDialog() == DialogResult.OK)
            {
                srvLst.Items.Clear();
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        private void srvLst_ItemActivate(object sender, EventArgs e)
        {
            if (new NewMessageForm(
                (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag)
                .ShowDialog() == DialogResult.OK)
            {
                srvLst.Items.Clear();
                srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        private void mnuNew_Click(object sender, EventArgs e)
        {
            srvLst_ItemActivate(null, null);
        }


        private void mnuSaved_Click(object sender, EventArgs e)
        {
            if (new MessagesSavedForm(
                (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag)
                .ShowDialog() == DialogResult.OK)
            {
                srvLst.Items.Clear();
                srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
            srvLst.Items.Clear();
            srvLst.Refresh();
            srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = false;
            new Thread(new ThreadStart(logic.LoadProcedure)).Start();
        }

        private void mnuSetup_Click(object sender, EventArgs e)
        {
            new ConfigForm().ShowDialog();
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        public void Logic_StatusTextChanged(String text)
        {
            if (InvokeRequired)
            {
                Logic.StatusTextChangedHandler func = Logic_StatusTextChanged;
                Invoke(func, text);
                return;
            }
            if (!stsBar.Visible)
                stsBar.Visible = stsBar.ProgressStarted = true;
            stsBar.Text = text;
        }

        public void Logic_ErrorCaused(String text)
        {
            if (InvokeRequired)
            {
                Logic.ErrorCausedHandler func = Logic_ErrorCaused;
                Invoke(func, text);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = true;
            MessageBox.Show(text, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        public void Logic_LoadProcedureClosed(List<Service> sl)
        {
            if (InvokeRequired)
            {
                Logic.LoadProcedureClosedHandler func = Logic_LoadProcedureClosed;
                Invoke(func, sl);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = true;

            foreach (Service s in sl)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = s.Name;
                lvi.Tag = s;
                lvi.ImageIndex = (int)s.Type;
                Int32 mex = s.MaxMessages;
                DateTime dt = s.Stat.Date;
                if ((s.MMMode == Service.MaxMessagesMode.DAILY &&
                    dt.Date == DateTime.Today) ||
                    (s.MMMode == Service.MaxMessagesMode.MONTHLY &&
                    dt.Month == DateTime.Today.Month &&
                    dt.Year == DateTime.Today.Year))
                    mex -= s.Stat.Sent;
                lvi.SubItems.Add(mex.ToString());
                srvLst.Items.Add(lvi);
            }
            srvLst.Refresh();
        }

        private class Logic
        {
            public delegate void StatusTextChangedHandler(String text);
            public event StatusTextChangedHandler StatusTextChangedEvent;

            public delegate void LoadProcedureClosedHandler(List<Service> lvis);
            public event LoadProcedureClosedHandler LoadProcedureClosedEvent;

            public delegate void ErrorCausedHandler(String text);
            public event ErrorCausedHandler ErrorCausedEvent;

            public void LoadProcedure()
            {
                FireStatusTextChanged(Utility.Tr("MainForm_stsLoad1", "Loading Services ..."));
                try
                {
                    Service[] sl = DBService.GetUsableServices();
                    FireLoadProcedureClosed(new List<Service>(sl));
                }
                catch (ObjectDisposedException e)
                {
                }
                catch (Exception e)
                {
                    FireErrorCaused(String.Format(Utility.Tr("MainForm_cantload", "Cannot load services data: {0}"), e.Message));
                }
            }

            private void FireErrorCaused(String text)
            {
                if (ErrorCausedEvent != null)
                    ErrorCausedEvent(text);
            }

            private void FireStatusTextChanged(String text)
            {
                if (StatusTextChangedEvent != null)
                    StatusTextChangedEvent(text);
            }

            private void FireLoadProcedureClosed(List<Service> lvis)
            {
                if (LoadProcedureClosedEvent != null)
                    LoadProcedureClosedEvent(lvis);
            }
        }

        private void srvLst_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (srvLst.SelectedIndices.Count > 0) {
                srvLst.ContextMenu = mnuContext;
                Service s = (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag;
                mnuSaved.Enabled = s.Messages.Count > 0;
                mnuLastSent.Enabled = s.LastMessage != null;
            } else
                srvLst.ContextMenu = null;
        }

        private void mnuLastSent_Click(object sender, EventArgs e)
        {
            Service s = (Service)srvLst.Items[srvLst.SelectedIndices[0]].Tag;
            if (new NewMessageForm(s, s.LastMessage).ShowDialog() == DialogResult.OK)
            {
                srvLst.Items.Clear();
                srvLst.Enabled = mnuServices.Enabled = mnuOther.Enabled = false;
                new Thread(new ThreadStart(logic.LoadProcedure)).Start();
            }
        }
    }
}